package futuretask;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Callable + Future
 */
public class AsynDemo {
    public static void main(String[] args) {
           // 初始化线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(5);

        // 初始化线程任务
        MyTask myTask = new MyTask(5);

        // 向线程池递交线程任务
        Future<Integer> result = threadPool.submit(myTask);

        // 主线程休眠2秒，模拟主线程在做其他的事情
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 主线程获取异步任务的执行结果
        try {
            System.out.println("异步线程任务执行结果 " + result.get());
            System.out.println("检查异步线程任务是否执行完毕 " + result.isDone());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

     // 静态内部类，实现Callable接口的任务类
    static class MyTask implements Callable<Integer> {
        private int num;

        public MyTask(int num) {
            this.num = num;
        }

        @Override
        public Integer call() throws Exception {
            for (int i = 1; i < 10; ++i) {
                this.num *= i;
            }
            return this.num;
        }
    }
}
